package com.viethp.mt.activities;

import java.util.ArrayList;
//import java.util.Random;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.viethp.mt.adapters.OActivityAdapter;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.customactivities.ATabActivityGroup;
import com.viethp.mt.objects.GetHaveListResponse;
//import com.viethp.mt.objects.GetWantListResponse;
import com.viethp.mt.objects.OActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class AGroupHave extends Activity implements OnItemClickListener,
		OnClickListener {

	private static final String ITEM_ID = "item_id";
	private static final String CATEGORY_ID = "category_id";
	private static final String ACTIVITY_ID = "activity_id";
	private static final String ITEM_TITLE = "title";
	private static final String ITEM_DESCRIPTION = "description";
	private static final String ITEM_EXP = "expired";
	private static final String ITEM_PRICE = "price";
	private static final String TOTAL_BIDDER = "total_bidder";
	private static final String MAX_BUDGET = "max_budget";
	// private static final String YOUR_PRICE = "your_price";
	private static final String ITEM_IMG_LINK = "imgLink";
	private static final String ITEM_STATUS = "status";

	private static final int REQUEST_DELETE = 102;

	private Button btn_want, btn_have, btn_refesh;
	private ListView lv_haves;
	private ArrayList<OActivity> list_Oactivities;
	private OActivityAdapter listOActivityAdapter;
	private ProgressDialog progressDialog;

	public View footerView;
	private int totaPages;
	private int pages;
	private TextView txtshowmore;

	// private int countDemo, num;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_list_have);

		initComponents();
		setOnClickListener();
	}

	public void initComponents() {
		btn_want = (Button) findViewById(R.id.btn_want);
		btn_have = (Button) findViewById(R.id.btn_have);
		btn_have.setClickable(false);
		btn_refesh = (Button) findViewById(R.id.btn_refesh);

		lv_haves = (ListView) findViewById(R.id.lv_have);
		list_Oactivities = new ArrayList<OActivity>();

		footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.listfooter, null, false);
		lv_haves.addFooterView(footerView);
		footerView.setVisibility(View.GONE);

		footerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (pages < totaPages) {
					pages++;
					initData();

				}

			}
		});
		listOActivityAdapter = new OActivityAdapter(this,
				R.layout.lv_activities, list_Oactivities);
		lv_haves.setAdapter(listOActivityAdapter);
		lv_haves.setOnItemClickListener(this);

		// add
		txtshowmore = (TextView) findViewById(R.id.idshow);

		progressDialog = new ProgressDialog(getParent());
		progressDialog.setCancelable(false);

		totaPages = 1;
		pages = 1;
		// countDemo=1;

		initData();
	}

	public void setOnClickListener() {
		btn_want.setOnClickListener(this);
		btn_refesh.setOnClickListener(this);
		// btn_have.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_want:
			ATabActivityGroup.group.back();
			break;
		case R.id.btn_refesh:
			pages = 1;
			// countDemo=1;
			list_Oactivities.removeAll(list_Oactivities);
			initData();
			break;
		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Intent item_details = new Intent(getApplicationContext(),
				AGroupHaveDetails.class);
		item_details
				.putExtra(ITEM_ID, String.valueOf(this.list_Oactivities.get(
						position).getItemID()));
		item_details.putExtra(ACTIVITY_ID, String.valueOf(this.list_Oactivities
				.get(position).getActivityID()));
		item_details.putExtra(ITEM_TITLE, String.valueOf(this.list_Oactivities
				.get(position).getItemTitle()));
		item_details.putExtra(ITEM_DESCRIPTION,
				String.valueOf(this.list_Oactivities.get(position).getDesc()));
		item_details.putExtra(ITEM_EXP,
				String.valueOf(this.list_Oactivities.get(position).getEXP()));
		item_details.putExtra(ITEM_PRICE, String.valueOf(this.list_Oactivities
				.get(position).getActivityPrice()));
		item_details.putExtra(TOTAL_BIDDER, String
				.valueOf(this.list_Oactivities.get(position).getTotalBidder()));
		item_details.putExtra(MAX_BUDGET, String.valueOf(this.list_Oactivities
				.get(position).getMaxBudget()));
		// item_details.putExtra(YOUR_PRICE,
		// String.valueOf(this.list_Oactivities.get(position).getYour()));
		item_details.putExtra(ITEM_IMG_LINK,
				String.valueOf(this.list_Oactivities.get(position).getIMG()));
		item_details.putExtra(CATEGORY_ID, String.valueOf(this.list_Oactivities
				.get(position).getCategoryId()));
		item_details.putExtra(ITEM_STATUS, String.valueOf(this.list_Oactivities
				.get(position).getActivityStatus()));
		getParent().startActivityForResult(item_details, REQUEST_DELETE);
		// startActivity(item_details);

	}

	private void startCallService() {

		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callService();
				handler.sendMessage(message);

			}
		}).start();

	}

	public void initData() {

		if (CommonHelper.isNetworkAvailable(this)) {
			startCallService();
		} else {
			CommonHelper.showWarning(this, getString(R.string.netstate));
		}

	}

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				GetHaveListResponse response = (GetHaveListResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(getParent(), response
							.getErrorCode().getErrMsg());
				} else {
					pages = response.getPage();
					totaPages = response.getTotalPage();
					ArrayList<OActivity> OactivityArr = response.getHaveArray();
					if (OactivityArr != null) {
						for (OActivity oa : OactivityArr) {
							list_Oactivities.add(oa);
						}
					}

					if (pages == totaPages) {

						if (lv_haves.getFooterViewsCount() != 0)
							lv_haves.removeFooterView(footerView);
						lv_haves.setFooterDividersEnabled(true);

					} else {
						footerView.setVisibility(View.VISIBLE);
						lv_haves.setFooterDividersEnabled(true);
						if (lv_haves.getFooterViewsCount() == 0)
							lv_haves.addFooterView(footerView);
					}

					txtshowmore.setText("Showing " + pages + " of " + totaPages
							+ " pages");
					listOActivityAdapter.notifyDataSetChanged();
				}

			} else {
				CommonHelper.showWarning(getParent(),
						getString(R.string.loaddatastate));

			}

		};
	};

	public GetHaveListResponse callService() {
		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_HAVE_LIST);
		userRequest.addProperty("user_id", CommonHelper.getUserLogin(this)
				.getId());
		userRequest.addProperty("page", pages);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_HAVE_LIST);
		request.addProperty(GlobalVariables.WS_METHOD_GET_HAVE_LIST,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_GET_HAVE_LIST, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_GET_HAVE_LIST, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		return new GetHaveListResponse(results);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("result", "test");
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_DELETE) {
				String delete_status = data.getStringExtra("delete_status");
				if (delete_status.equals("delete")) {
					pages = 1;
					list_Oactivities.removeAll(list_Oactivities);
					initData();
				}
			}
		}
	}

}
